<script setup>
import { ref } from "vue";
import { getOrderListService } from "@/api/orders";
import { debounce } from "lodash";
import { onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useUserInfoStore } from "@/stores/userInfo.js";
import { updateOrderService } from "@/api/orders";
import { updateOrderAddressService } from "@/api/address";

// 用户数据
const userInfoStore = useUserInfoStore();
// 监听事件
onMounted(() => {
  window.addEventListener("scroll", handleScroll);
  // 重置订单列表
  resetOrderList();
});
// 屏幕滚动事件（自动添加商品列表）
// 注意：滚动调用时有时候会多次触发，所以需要做好防抖处理
const handleScroll = debounce(() => {
  let scrollTop = window.scrollY || document.documentElement.scrollTop;
  let windowHeight = window.innerHeight;
  let documentHeight = document.documentElement.scrollHeight;
  // 检查是否到达底部
  if (scrollTop + windowHeight >= documentHeight - 50 && loading.value) {
    console.log("到达底部");
    getOrderList(); // 调用接口加载更多商品
    window.scrollTo({
      top: scrollTop - 200, // 向上滚动200像素
      behavior: "smooth", // 平滑滚动
    });
  }
}, 300);

// 当前页码
const pageNum = ref(1);
// 商品列表是否继续加载
const loading = ref(true);
// 商品列表
// 获取订单信息
const getOrderList = async () => {
  // 调用接口获取订单列表
  const res = await getOrderListService(pageNum.value);
  if (res.code === 1) {
    loading.value = false;
    console.log("loading == false");
    return;
  }
  // 添加数据
  for (let i = 0; i < res.data.length; i++) {
    userInfoStore.order.push(res.data[i]);
  }
  console.log(userInfoStore.order); 
  pageNum.value++;
  // 更新未付款订单信息
  updateUnpaidOrder();
};
getOrderList(); // 初始加载订单列表
// 重置订单信息
const resetOrderList = () => {
  userInfoStore.order = [];
  pageNum.value = 1;
  loading.value = true;
};

// 弹出框是否显示
const centerDialogVisible = ref(false);
// 订单状态更新
const updateOrderStatus = async (status) => {
  if (UnpaidOrder.value.length == 0) {
    ElMessage.error("您没有可以取消或付款的订单");
    return;
  }
  // 去付款
  if (status == 1) {
    // 计算未付款订单总金额
    let totalAmount = 0;
    userInfoStore.order.some((order) => {
      if (order.status === 1) {
        totalAmount += order.totalPrice;
        return false; // 继续遍历
      }
      return true; // 当status不是1时，停止遍历（订单状态是连续的）
    });

    window.open(
      "http://127.0.0.1:8081/alipay/pay?subject=" +
        userInfoStore.order[0].commodity.commodityTitle.substr(0, 8) +
        "..." +
        "&traceNo=" +
        userInfoStore.order[0].ordersId +
        "&totalAmount=" +
        totalAmount +
        "&userId=" +
        userInfoStore.info.userId,
      "_self"
    );
  } else if (status == 5) {
    // 取消订单
    let res = await updateOrderService(5, userInfoStore.order[0].ordersId);
    ElMessage.success(res.code == 0 ? "取消订单成功" : "取消订单失败");
    // 刷新订单列表
    resetOrderList();
    getOrderList();
  }
  centerDialogVisible = false;
};
// 待付款订单信息
const UnpaidOrder = ref([]);
// 更新未付款订单信息
const updateUnpaidOrder = () => {
  try {
    // 筛选未付款订单并更新
    UnpaidOrder.value = userInfoStore.order.filter(
      (order) => order.status === 1
    );
  } catch (error) {
    console.error("更新未付款订单信息时出错:", error);
    ElMessage.error("更新未付款订单信息失败，请稍后重试。");
  }
  console.log(UnpaidOrder.value);
};

// 选中的订单的id
let selectedOrderDetailId = null;
// 选择的地址信息
let selectedAddress = {};
// 修改地址
const updateAddress = async () => {
  // 调用接口修改地址信息
  let res = await updateOrderAddressService(selectedOrderDetailId, {
    addressId: selectedAddress.addressId,
    receiverName: selectedAddress.receiverName,
    receiverPhone: selectedAddress.receiverPhone,
    receiverAddressDescription: selectedAddress.receiverAddressDescription,
  });
  ElMessage.success(res.message);
  // 刷新订单列表
  userInfoStore.order = [];
  pageNum.value = 1;
  loading.value = true;
  getOrderList();
};

// 修改地址按钮
const addressDialogVisible = ref(false);

// 地址选择状态
const addressSelectedStatus = (val) => {
  if (val.selected == true) {
    val.selected = false;
    selectedAddress = {};
    return;
  }
  // 将所有地址的selected属性设置为false
  userInfoStore.address.forEach((element) => {
    element.selected = false;
  });
  // 将选中的地址的selected属性设置为true
  val.selected = true;
  // 保存选中的地址信息
  selectedAddress = {
    addressId: val.addressId,
    receiverName: val.addressName,
    receiverPhone: val.addressPhone,
    receiverAddressDescription: val.addressDescription
  };
  console.log('选中的地址信息:', selectedAddress);
};
</script>

<template>
  <el-container class="container">
    <el-header>
      <el-row>
        <!-- 标题 -->
        <el-col class="recommend-commodity-title" :span="24">
          <text>订单列表</text>
        </el-col>
      </el-row>
    </el-header>
    <el-main class="main-container">
      <el-row>
        <!-- 订单列表 -->
        <el-col :span="24">
          <el-table class="table-container" :data="userInfoStore.order">
            <el-table-column align="center" label="商品" width="130">
              <template #default="scope">
                <router-link
                  :to="`/commodity/detail/${scope.row.commodity.commodityId}`"
                >
                  <img
                    class="commodity-img"
                    :src="scope.row.commodity.coverImage"
                    alt=""
                  />
                </router-link>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              width="250"
              class="commodity-title"
              prop="commodity.commodityTitle"
              label="标题"
            >
            </el-table-column>
            <el-table-column label="规格" width="150">
              <template #default="scope">
                <span v-for="(item, index) in scope.row.sku.specs" :key="index"
                  >{{ item.name }}: {{ item.valueName }}<br
                /></span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="数量"
              width="100"
              prop="quantity"
            >
            </el-table-column>
            <el-table-column label="收货信息" width="250">
              <template #default="scope">
                <div
                  v-if="scope.row.status == 1 || scope.row.status == 2"
                  class="address-column"
                  @click="
                    (addressDialogVisible = true),
                      userInfoStore.address.forEach((element) => {
                        element.selected = false;
                      }),
                      (selectedOrderDetailId = scope.row.orderDetailId)
                  "
                >
                  姓名：
                  {{ scope.row.receiverName }}<br />
                  手机号：
                  {{ scope.row.receiverPhone }}<br />
                  收货地址：
                  {{ scope.row.receiverAddressDescription }}
                </div>
                <div v-else>
                  姓名：
                  {{ scope.row.addressName }}<br />
                  手机号：
                  {{ scope.row.addressPhone }}<br />
                  收货地址：
                  {{ scope.row.addressDescription }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="支付金额" width="100">
              <template #default="scope">
                <text class="cart-price"> {{ scope.row.totalPrice }}￥ </text>
              </template>
            </el-table-column>
            <el-table-column align="center" width="150" label="支付状态">
              <template #default="scope">
                <text class="cart-price" v-if="scope.row.status == 1">
                  待付款
                </text>
                <text v-if="scope.row.status == 2"> 已付款 </text>
                <text v-if="scope.row.status == 3"> 已发货 </text>
                <text v-if="scope.row.status == 4"> 已完成 </text>
                <text v-if="scope.row.status == 5"> 取消订单 </text>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="200">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status == 1"
                  type="success"
                  @click="centerDialogVisible = true"
                >
                  去付款
                </el-button>
                <el-button
                  v-if="scope.row.status == 1"
                  type="danger"
                  @click="centerDialogVisible = true"
                >
                  取消订单
                </el-button>
                <br />
                <br />
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
  <!-- 订单弹出框 -->
  <el-dialog
    v-model="centerDialogVisible"
    title="以下订单需要一起付款或取消订单"
    width="700"
    align-center
  >
    <div
      class="tip-container"
      v-for="(order, index) in UnpaidOrder"
      :key="index"
    >
      <span>{{ order.commodity.commodityTitle }}</span>
      <span style="float: right"> {{ order.totalPrice }}￥ </span>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          style="float: left"
          @click="(centerDialogVisible = false), updateOrderStatus(5)"
          >取消订单</el-button
        >
        <el-button
          type="primary"
          @click="(centerDialogVisible = false), updateOrderStatus(1)"
        >
          去付款
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 地址弹出框 -->
  <!-- 此标签的style放在style标签中会失效？？？ -->
  <el-dialog
    style="
      max-height: 500px;
      max-width: 1000px;
      overflow-y: auto;
      overflow-x: hidden;
    "
    v-model="addressDialogVisible"
    title="更改收货地址"
    align-center
  >
    <div v-for="(item, index) in userInfoStore.address" :key="index">
      <el-button
        class="address-dialog-btn"
        :class="{
          selected: item.selected,
        }"
        @click="addressSelectedStatus(item)"
      >
        <tbody>
          <tr>
            <td>收货人：</td>
            <td>{{ item.addressName }}</td>
          </tr>
          <tr>
            <td>手机号：</td>
            <td>{{ item.addressPhone }}</td>
          </tr>
          <tr>
            <td>收货地址：</td>
            <td>{{ item.addressDescription }}</td>
          </tr>
        </tbody>
      </el-button>
    </div>
    <template #footer>
      <div>
        <el-button style="float: left" @click="$router.push('/address')">
          新建地址
        </el-button>
        <el-button
          type="primary"
          @click="(addressDialogVisible = false), updateAddress()"
        >
          更改收货地址
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>



<style scoped lang = "scss">
@import "@/assets/style/config.scss";

@mixin sku-state-mixin {
  &.selected {
    border: 1px solid;
    border-color: $themeColor;
    background-color: $themeColor;
    color: white;
  }

  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}

.el-dialog {
  .el-dialog__footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px 20px;
    background: white;
    border-top: 1px solid #ebeef5;
    z-index: 10;
  }
}

// 结算框中的公共样式
$fontSize: 18px;
$priceColor: rgb(190, 36, 36);

.container {
  width: 100%;
}
.commodity-img {
  width: 100px;
  border-radius: 15px;
}
.main-container {
  margin: 0 auto;
}

.recommend-commodity-title {
  text-align: center;
  font-size: 30px;
}

.table-container {
  font-size: 16px;
}
.cart-price {
  color: $priceColor;
  font-size: 15px;
}
.aside {
  width: 25%;
}
.aside-container {
  position: fixed;
  border: 1px solid $themeColor;
  border-radius: 15px;
  padding: 10px;
}

.account-title {
  font-size: $fontSize;
  margin-bottom: 20px;
}
.account-tip {
  margin: 0 auto;
  width: 100px;
  margin-top: 10%;
  margin-bottom: 10%;
  font-size: $fontSize;
}
.account-img {
  height: 40vh; /* 设置容器的高度 */
  overflow-y: auto; /* 超出容器高度时，出现垂直滚动条 */
  overflow-x: hidden; /* 隐藏横向滚动条 */
}
.account-total {
  // 设置合计的边距
  margin: 20px 0;
  font-size: $fontSize;
}
.total-price {
  color: $priceColor;
  font-size: $fontSize;
}
.account-image {
  width: 100px;
  border-radius: 15px;
  margin: 3px;
}
.account-btn {
  width: 100%;
  height: 50px;
  font-size: 18px;
  background-color: #eb7c44;
  border: none;
}
.tip-container {
  font-size: 16px;
  padding: 5px;
}
.address-column:hover {
  border: 1px solid $themeColor;
  border-radius: 10px;
}
.address-dialog-btn {
  width: auto;
  height: auto;
  text-align: left;
  font-size: 16px;
  margin: 5px;
  @include sku-state-mixin;
}
</style>